package com.suneee.base.processor;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.suneee.context.processor.AnnotationProcessor;
import com.suneee.context.util.JsonNodeUtils;
import com.suneee.core.error.ErrorUtils;
import com.suneee.core.error.GenericError;
import com.suneee.core.type.json.JsonUtils;

public class StaticResourceProcessor implements AnnotationProcessor<StaticResource> {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Override
	public boolean processAnnotation(Class<?> type, StaticResource annotation) {
		logger.info("读取静态资源：" + type.getName());
		String group = annotation.key();
		ObjectNode resourceNode = (ObjectNode) JsonNodeUtils.get(group);
		if (resourceNode == null) {
			resourceNode = JsonUtils.mapper().createObjectNode();
			JsonNodeUtils.put(group, resourceNode);
		} else {
			throw ErrorUtils.wrap(GenericError.DUPLICATE_RESOURCE_PATH, group);
		}
		
		StaticResourceProvider provider =new StaticResourceProvider();
		Properties props =provider.getProps();
		Iterator<?> it=props.entrySet().iterator();
		ObjectMapper mapper = JsonUtils.reader();
		while(it.hasNext()){
		    Map.Entry<Object,Object> entry=(Map.Entry)it.next();
		    Object key = entry.getKey();
		    Object value = entry.getValue();
		    try {
				JsonNodeUtils.put(group+"."+key,mapper.readTree(String.valueOf(value)));
			} catch (IOException e) {
				throw ErrorUtils.wrap(GenericError.DUPLICATE_RESOURCE_PATH, group+"."+key);
			}
		}
		return false;
	}

}
